import {Prisma} from '@/generated/prisma';
import {db} from '@/lib/db'

export async function getSecuPrice(code: string): Promise<number> {
    const current = await db.dest_current.findUnique({
        where: {
            secu_code: code
        }
    });
    return current?.price || 0;
}

export async function getSecuInfo(code: string) {
    return db.tb_info.findUnique({
        where: {
            secu_code: code,
        }
    });
}

export async function getSecuExpect(code: string) {
    return db.tb_expect.findUnique({
        where: {
            secu_code: code
        }
    })
}

export async function getSecuBlocks(code: string) {
    return db.$queryRaw`
        SELECT secu_code, block_name, block_explain, block_source
        FROM tb_block
        WHERE secu_code = ${code}
          AND updated_at >= current_timestamp - '90 DAY'::interval
    `;
}

export async function getBlocksBySecuCode(...codes: string[]) {
    if (codes.length === 0) return []
    return db.tb_block.findMany({
        where: {
            secu_code: {
                in: codes
            }
        }
    })
}

export async function getBriefs(code: string) {
    return db.$queryRaw`
    select secu_code,secu_name ,brief_title ,brief_reason ,brief_source ,brief_date from (
      select row_number() over (partition by secu_code,brief_source order by brief_date desc) as rn, secu_code,secu_name ,brief_title ,brief_reason ,brief_source ,brief_date from tb_brief where brief_source!='gnn'
    )where rn=1 and secu_code=${code}
  `;

}

export async function getTopRanks() {
    const result: any = await db.$queryRaw`
        select array_agg(k) as top_ranks from (select distinct k from mv_art_ks_24h a where exists(select 1 from mv_dixi_ks b where a.k=b.k) or exists(select 1 from mv_search_ks_24h c where a.k=c.k)) 
    `;
    // console.log(typeof result)
    const {top_ranks: rankList}: { top_ranks: string[] } = result[0]
    if (rankList && rankList.length > 0) {
        return rankList.map((r: string) => {
                return {rank_name: r}
            }
        )
    }
    return []
}

export async function getSecuCurrent(codes: string[]) {
    return db.dest_current.findMany({
        where: {
            secu_code: {
                in: codes
            }
        }
    })
}

export async function getTopNB1amt(n: number = 7) {
    return db.dest_current.findMany({
        where: {
            zt: 1,

        },
        orderBy: {
            b1amt: "desc"
        },
        take: n
    });
}


export async function getRisk(code: string) {
    return db.tb_zdjk.findFirst({
        where: {
            secu_code: code
        }
    });

}

export async function getReports(code: string) {
    return db.$queryRaw`
    with 
	    cte as (select secu_name,expect || brief_keys || tokens as tokens from v_expect where secu_code = ${code})
    select 
        report_id,publish_time,title,org_name,abstract,
        pgroonga_snippet_html(title,tokens) as highlight_title,
        pgroonga_snippet_html(abstract,array[secu_name],100) as highlight_abstract,
        tokens
    from tb_report,cte
    where 1=1 
        and abstract &@~ secu_name
        and not title &~ '周报|日报'
        and publish_time >= current_timestamp - '4 days'::interval
    order by publish_time desc
    limit 10;
  `;
}